package com.xunwulian.dubbo.service.impl;

import com.google.gson.Gson;
import com.xunwulian.api.dto.BaseResponse;
import com.xunwulian.api.iface.SmsAPI;
import com.xunwulian.base.constant.ConstantBean;
import com.xunwulian.base.constant.SmsStatus;
import com.xunwulian.base.constant.SmsType;
import com.xunwulian.base.dao.AppDao;
import com.xunwulian.base.dao.CardInfoDao;
import com.xunwulian.base.dao.SmsPocessorDao;
import com.xunwulian.base.dao.UserDao;
import com.xunwulian.base.entity.*;
import com.xunwulian.base.util.DateUtil;
import com.xunwulian.base.util.SeqUtil;
import com.xunwulian.base.util.TextUtil;
import com.xunwulian.cmpp.pdu.Submit;
import com.xunwulian.dubbo.handler.Consumer;
import com.xunwulian.dubbo.iface.CmppSmsAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SmsApiImpl implements SmsAPI {

    protected static final Logger logger = LoggerFactory.getLogger(SmsApiImpl.class);

    @Autowired
    private AppDao appDao;

    @Autowired
    private CardInfoDao cardInfoDao;

    @Autowired
    private SmsPocessorDao smsPocessorDao;

    @Autowired
    private UserDao userDao;

//    @Reference
//    CmppSmsAPI cmppSmsAPI;

    public SmsApiImpl() {
    }

    /**
     * 发送短信
     *
     * @param userId
     * @param msisdn
     * @param content
     * @param appId
     * @return
     */
    @Override
    public BaseResponse send(String userId, String msisdn, String content, String appId) {

        String clientServiceId = ConstantBean.ZXTD_CMPP_CLIENT_SERVICEID;
        String clientSrcId = ConstantBean.ZXTD_CMPP_CLIENT_SRCID;
        String serverClientId = ConstantBean.ZXTD_CMPP_SERVER_CLIENTID;

        logger.info("appId:", appId);

        AppEntity appEntity = appDao.getById(appId);
        if (appEntity != null) {
            clientServiceId = appEntity.getClientServiceId();
            clientSrcId = appEntity.getClientSrcId();
            serverClientId = appEntity.getServerClientId();
        }

        long seqId = SeqUtil.getSeq();

        logger.info("appEntity:", appEntity.getRegistryAddress());

        // 发送短信消息
        Submit submit = new Submit(new String[]{msisdn}, (int) seqId, content,
                clientServiceId, clientSrcId, serverClientId);
//        CmppSmsAPI cmppSmsAPI = smsConsumer.getCmppSmsApi(appId);

        CmppSmsAPI api = new Consumer<CmppSmsAPI>().getApi(CmppSmsAPI.class, appId, appId, appEntity.getRegistryAddress());
        api.sendCmppSms(submit);

        logger.info("appId:" + appId + ".sender");

        User user = userDao.getByUid(userId);

        // 短信写入数据库
        SmsPocessorEntity smsPocessorEntity = new SmsPocessorEntity(msisdn,
                SmsType.SEND.type,
                content,
                userId,
                user.getUSERNAME(),
                SmsStatus.SENT.type,
                seqId,
                appId);

        smsPocessorDao.insert(smsPocessorEntity);

        return new BaseResponse();
    }

    /**
     * 前十最热短信
     *
     * @param userId
     * @return
     */
    @Override
    public BaseResponse getHostList(String userId) {

        List<HotestSmsBean> resultList = smsPocessorDao.listHotSmsByUserId(userId, SmsType.SEND.getType(), 10);

        List<String> result = resultList.stream().map(p -> TextUtil.encodeHtml(p.getContent())).collect(Collectors.toList());

        BaseResponse<List<String>> response = new BaseResponse<>();
        response.setData(result);

        return response;
    }

    /**
     * 查询发送频率
     *
     * @param userId
     * @param msisdn
     * @param content
     * @return
     */
    @Override
    public BaseResponse checkFrequence(String userId, String msisdn, String content) {

        // 三分钟内
        Date createTime = DateUtil.addSecond(new Date(), -180);

        Integer cnt = smsPocessorDao.checkFrequence(userId, msisdn, content, SmsType.SEND.getType(), createTime);

        BaseResponse<Integer> response = new BaseResponse<>();
        response.setData(cnt);

        return response;
    }

    /**
     * 接收到回复短信
     *
     * @param msisdn
     * @param content
     * @param seqId
     * @return
     */
    @Transactional
    @Override
    public BaseResponse addSms(String msisdn, String content, long seqId) {

        SmsPocessorEntity latestSend = smsPocessorDao.getLatestSendByMsisdn(SmsType.SEND.getType(), msisdn);

        // 最后默认userId为1，admin
        String userId = ConstantBean.ADMIN_USER_ID;
        String userName = ConstantBean.ADMIN_USER_NAME;
        String appId = ConstantBean.DEFAULT_APPID;

        if (latestSend != null) {
            userId = latestSend.getUserId();
            userName = latestSend.getUserName();
            appId = latestSend.getAppId();
        } else {
            CardInfoEntity cardInfoEntity = cardInfoDao.getByMsisdn(msisdn);
            if (cardInfoEntity != null) {
                if (! ("".equals(cardInfoEntity.getSubUserId()) || cardInfoEntity.getSubUserId() == null)) {
                    userId = cardInfoEntity.getSubUserId();
                } else if (!("".equals(cardInfoEntity.getUserId()) || cardInfoEntity.getUserId() == null )) {
                    userId = cardInfoEntity.getUserId();
                }
            }
        }

        // 写入短信
        SmsPocessorEntity smsPocessorEntity = new SmsPocessorEntity(msisdn,
                SmsType.RECEIVE.type,
                content,
                userId,
                userName,
                SmsStatus.RECEICED.type,
                seqId,
                appId);

        smsPocessorDao.insert(smsPocessorEntity);

        // 扣减短信费用
//        userDao.increaseBalance(userId, ConstantBean.SMS_FEE_UNIT);

        // 写入消费流水
//        TransactionEntity trans = new TransactionEntity(UuidUtil.get32UUID(),
//                TransType.SMS_CONSUME.getType(),
//                TransStatus.SUCCESS.getType(),
//                ConstantBean.SMS_FEE_UNIT,
//                userId,
//                userId);
//        transactionDao.insert(trans);

        Gson gson = new Gson();
        logger.info("smsPocessorEntity:" + gson.toJson(smsPocessorEntity));

        return new BaseResponse();
    }

    /**
     * 发送成功通知
     *
     * @param seqId
     * @return
     */
    @Override
    public BaseResponse noticeReply(long seqId, int result, String code, String msg) {

        // 更新发送结果
        if (result == 0) {
            smsPocessorDao.updateStatus(SmsStatus.SENT.type, seqId);
        } else {
            smsPocessorDao.updateStatus(SmsStatus.SEND_FAILED.type, seqId);
        }

        return new BaseResponse();
    }

    /**
     * 分页获取短信列表
     */
    @Override
    public BaseResponse listPage(Page page,
                                 String appId,
                                 String userId,
                                 String msisdnKey,
                                 String userNameKey,
                                 Integer typeId) {

        List<SmsPocessorEntity> list = smsPocessorDao.listPage(page,
                appId,
                userId,
                msisdnKey,
                userNameKey,
                typeId);

        BaseResponse response = new BaseResponse();
        response.setData(list);
        response.setPage(page);

        return response;
    }

    /**
     * 分页统计用户收发
     *
     * @param userId
     * @param userName
     * @return
     */
    @Override
    public BaseResponse listPageStatByUser(Page page,
                                           String userId,
                                           String userName) {

        List<SmsPocessorCountByUserEntity> list = smsPocessorDao.listPageStatByUser(page, userId, userName);

        BaseResponse response = new BaseResponse();
        response.setPage(page);
        response.setData(list);

        return response;
    }
}
